import api from '../../Sendingmethod/Sendingmethod'
import {
    Bseurl
} from "../../baseurl/baseurl"
import
encrypt
from "../../utils/crypto-util.js"
import util from '../../utils/util'
// pages/personal/personal.js
Page({

    /**
     * 页面的初始数据
     */
    data: {
        // 正面
        frontimg: "",
        // 反面
        tailsimg: '',
        //输入框
        fromarr: [{
                text1: "商家名称",
                value: "",
                title: "nickname"
            },

            {
                text1: "真实姓名",
                value: "",
                title: "realname"
            },
            {
                text1: "居民身份证",
                value: "",
                title: "idcard"
            },
            {
                text1: "联系电话",
                value: "",
                title: "mobile"
            },
            {
                text1: "电子邮箱",
                title: "email",
                value: ""
            },
        ],
        //全部成功
        alltext: true,
        //弹出框控制
        showblem: false,
        emailtext: '@',
        personalEmailDomains: [{
                domain: "@qq.com"
            }, // 腾讯旗下主力邮箱
            {
                domain: "@163.com" // 网易经典邮箱

            },
            {
                domain: "@sina.com" // 新浪邮箱

            },
            {
                domain: "@139.com" // 中国移动运营商邮箱

            },
            {
                domain: "@gmail.com" // Google 邮箱（国际通用）
            }
        ],
        emlistblen: false,
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad(options) {
        if (wx.getStorageSync('token')) {
            this.getinfo()
        }

    },
    /**
     * 
     * 邮箱控制
     */
    emakong() {
        this.setData({
            emlistblen: !this.data.emlistblen
        })
    },
    /**
     * 
     * 尾缀选择
     */
    weizhuixuanze(e) {
        console.log(e);
        this.setData({
            emailtext: e.currentTarget.dataset.em
        })
    },
    /**
     * 输入事件
     */
    inputfun(e) {
        console.log(e, e.target.dataset.index, '输入');
        this.data.fromarr[e.target.dataset.index].value = e.detail.value
        this.panduan()
    },
    /**
     * 非空判断
     */
    panduan() {
        const filteredArray = this.data.fromarr.filter(item => item.value == "");
        if (filteredArray.length > 0) {
            this.setData({
                alltext: false
            })
            console.log(filteredArray, "未填写");
        } else {
            if (this.data.frontimg == '' || this.data.tailsimg == '') {
                console.log('图片未传');
            } else {
                console.log('放行');
                this.setData({
                    alltext: true
                })
            }
        }
    },
    /**
     * 图片选择
     */
    updateimg(e) {
        let _that = this
        console.log(e.target.dataset.type);
        wx.chooseMedia({
            count: 1, // 可选择的图片数量
            mediaType: ['image'],
            sizeType: ['compressed'], // 压缩图片
            sourceType: ['album', 'camera'], // 来源：相册或相机
            success: (res) => {
                console.log(res);
                // 将选择的图片上传到服务器
                // this.uploadImage(res.tempFilePaths[0]);
                // if(res.code==0){
                if (e.target.dataset.type == 'front') {
                    console.log(res.tempFiles[0].tempFilePath);
                    // this.setData({
                    //     frontimg: res.tempFiles[0].tempFilePath
                    // })
                    this.imgeuplode(res.tempFiles[0], 'front')
                }
                if (e.target.dataset.type == 'tails') {
                    console.log(res.tempFiles[0].tempFilePath);
                    // this.setData({
                    //     tailsimg: res.tempFiles[0].tempFilePath
                    // })
                    this.imgeuplode(res.tempFiles[0], 'tails')
                }
                this.panduan()

            }
        })
    },
    /**分割邮箱 */
    splitEmail(email) {
        const [local, domain] = email.split('@'); // 按 @ 分割成数组
        return {
            local,
            domain
        }; // 返回分割后的对象
    },
    /**
     * 如果用户提交过获取用户信息 获取它
     */
    async getinfo() {
        console.log(this.data.fromarr, '赋值过后的');
        try {
            let res = await api.getorpost_info({
                op: 'info'
            })
            if (res.code == 0) {
                console.log(res, '获取的个人信息');
                let data = res.data
                let newarr
                if (data.idcardfront) {
                    console.log('如果已上传 身份证正面');
                    this.setData({
                        // 正面
                        frontimg: data.idcardfront,
                    })
                }
                if (data.idcardback) {
                    console.log('如果已上传 身份证背面');
                    this.setData({
                        //反面
                        tailsimg: data.idcardback
                    })
                }
                this.data.fromarr.forEach(item => {
                    console.log(data[item.title], '记录过的数据');
                    if (item.title && data.hasOwnProperty(item.title)) {
                        if (item.title == "email") {
                            let newobj = this.splitEmail(data[item.title])
                            console.log(newobj, '分解后的邮箱');
                            // 分解后依次赋值
                            item.value = newobj.local
                            this.setData({
                                emailtext: '@' + newobj.domain
                            })
                        } else {
                            item.value = data[item.title];
                        }

                    }
                });
                newarr = this.data.fromarr
                this.setData({
                    fromarr: newarr
                })

                this.panduan()
            } else {

            }
        } catch (error) {
            wx.showToast({
                title: '请求失败',
                icon: 'error',
                duration: 2000
            })
        }

    },
    /**
     * 提交审核
     */
    async postinfo() {
        wx.showLoading({
            mask: true
        })
        let newobj = {
            idcardfront: this.data.frontimg,
            idcardback: this.data.tailsimg,
        }
        this.data.fromarr.forEach((item, index) => {
            console.log(item.value);
            console.log(item.title);
            newobj = {
                ...newobj,
                ...{
                    [item.title]: item.value
                },
            }

        })
        newobj.email= newobj.email+this.data.emailtext
        console.log(newobj, '需要上传的数据');

        try {
            let res = await api.getorpost_info({
                op: 'edit',
                ...newobj
            })
            if (res.code == 0) {
                wx.hideLoading()
                console.log(res, '送审数据成功');
                this.setData({
                    showblem: true
                })
                setTimeout(() => {
                    wx.reLanch({
                        url: '/pages/Login/Login',
                    })
                }, 500)

            } else {
                wx.showToast({
                    title: '上传失败',
                    icon: res.msg,
                    duration: 2000
                })

            }
        } catch (error) {
            wx.hideLoading()
            wx.showToast({
                title: '请求失败',
                icon: 'error',
                duration: 2000
            })
        }
    },
    tijiaofagdu: util.throttle(function () {
        this.postinfo()
    }, 1000),
    getUuid() {
        return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
            var r = (Math.random() * 16) | 0,
                v = c == 'x' ? r : (r & 0x3) | 0x8;
            return v.toString(16);
        });
    },

    /**
     * 身份证上传
     * 
     */
    imgeuplode(data, imgtype) {
        wx.showLoading({
            mask: true
        })
        // 获取当前时间戳
        let datatime = new Date().getTime()
        console.log(data);
        let Randomnum = this.getUuid()
        let aecdata
        let md5
        let _that = this
        let fromarr2 = `fromarr[${2}].value`;
        let fromarr1 = `fromarr[${1}].value`;
        md5 = encrypt.md5(`sign:data=&nonceStr=${Randomnum}&timestamp=${datatime}`)
        wx.uploadFile({
            url: 'https://api.business.dayenginer.com/user/idcard',
            filePath: data.tempFilePath,
            formData: {},
            name: 'file',
            header: {
                "h_uid": wx.getStorageSync('userid') ? wx.getStorageSync('userid') : '',
                "h_timestamp": datatime,
                "h_nonceStr": Randomnum,
                "h_sign": md5,
                "h_token": wx.getStorageSync('token') ? wx.getStorageSync('token') : '',
                "h_deviceId": '',
                'Content-Type': 'multipart/form-data'
            },
            success(res) {
                console.log(res, "上传成功");
                let data = JSON.parse(encrypt.aesDecrypt(res.data))
                console.log(data);
                wx.hideLoading()
                //判断

                if (imgtype == 'front') {
                    if (data.data.idcard) {
                        wx.showToast({
                            title: '上传成功',
                            icon: 'success',
                            duration: 2000
                        })
                        _that.setData({
                            frontimg: data.data.url,
                            [fromarr2]: data.data.idcard,
                            [fromarr1]: data.data.realname,
                        })
                    } else {
                        wx.showToast({
                            title: '请上传正面',
                            icon: 'error',
                            duration: 2000
                        })
                    }
                }
                if (imgtype == 'tails') {
                    if (data.data.idcard) {

                        wx.showToast({
                            title: '请上传背面',
                            icon: 'error',
                            duration: 2000
                        })

                    } else {
                        wx.showToast({
                            title: '上传成功',
                            icon: 'success',
                            duration: 2000
                        })
                        _that.setData({
                            tailsimg: data.data.url
                        })
                    }

                }
                _that.panduan()
            },
            fail(res) {
                console.log(res, '上传失败');
                console.log(JSON.parse(encrypt.aesDecrypt(res.data)));
                wx.hideLoading()
            }
        })
    },
    /**
     * 提交审核
     */
    tijiaoshenghe() {
        console.log('提交审核');
        // this.setData({
        //     showblem: true
        // })
        // setTimeout(() => {
        //     wx.redirectTo({
        //         url: "/pages/Login/Login"
        //     });
        // }, 1000)
    },








    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady() {

    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow() {

    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide() {

    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload() {

    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh() {

    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom() {

    },

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage() {

    }
})